package com.spring.sunflower.base;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Build;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;

import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.spring.sunflower.R;
import com.spring.sunflower.common.WebViewActivity;
import com.spring.sunflower.constant.Constant;
import com.spring.sunflower.dialog.OnPermissionIntroClickListener;
import com.spring.sunflower.util.ActivityManager;
import com.spring.sunflower.util.StatusBarUtil;
import com.spring.sunflower.widget.GlideEngine;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

/**
 * Created by Kevin on 2021/5/19<br/>
 * <p>
 * Describe:<br/>
 */
public abstract class BaseCompatActivity extends AppBaseActivity {
    public TextView tvTitle;
    public boolean mGrantedCameraPermission;
    public boolean mGrantedStoragePermission;
    public boolean mGratedRecordPermission;

    @Override
    public void onStart() {
        super.onStart();
        if (shouldRegisterEventBus()) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (shouldRegisterEventBus()) {
            EventBus.getDefault().unregister(this);
        }
    }

    public boolean shouldRegisterEventBus() {
        return false;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
//        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        doSomethingBeforeOnCreate();
        super.onCreate(savedInstanceState);
        setContentView(getLayoutID());
        mGrantedCameraPermission = XXPermissions.isGranted(this, Permission.CAMERA);
        mGrantedStoragePermission = XXPermissions.isGranted(this, Permission.READ_EXTERNAL_STORAGE, Permission.WRITE_EXTERNAL_STORAGE);
        mGratedRecordPermission = XXPermissions.isGranted(this, Permission.RECORD_AUDIO);
        Toolbar toolBar = findViewById(R.id.toolBar);
        tvTitle = findViewById(R.id.tvTitle);
        if (toolBar != null) {
            setSupportActionBar(toolBar);
        }
        ActionBar supportActionBar = getSupportActionBar();
        if (supportActionBar != null) {
            printD("supportActionBar != null");
            supportActionBar.setDisplayHomeAsUpEnabled(true);
            supportActionBar.setHomeButtonEnabled(true);
            supportActionBar.setTitle("");
        } else {
            printD("supportActionBar == null");
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        } else {
            StatusBarUtil.StatusBarLightMode(this);
        }
        initView();
    }


    public abstract int getLayoutID();

    public abstract void initView();

    @Override
    protected void onResume() {
        super.onResume();
        ActivityManager.getActivityManager().pushActivity(this);
        if (mApp != null) {
            mApp.setCurrentActivity(this);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        ActivityManager.getActivityManager().popActivity(this);
        clearCurrentActivity();
    }

    public void startNewActivity(Class<? extends BaseActivity> clazz) {
        Intent intent = new Intent(this, clazz);
        startActivity(intent);
    }

    public void startCompatActivity(Class<? extends BaseCompatActivity> clazz) {
        Intent intent = new Intent(this, clazz);
        startActivity(intent);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        printD("onOptionsItemSelected==" + (item.getItemId() == android.R.id.home));
        switch (item.getItemId()) {
            case android.R.id.home:
                onBackPressed();
                break;
        }
        return true;
    }

    public void doSomethingBeforeOnCreate() {

    }

    //    public void clearStorageUserData() {
//        saveField(Constant.KEY_TOKEN, "");
//        saveField(Constant.KEY_GENDER, "");
//        saveField("birthday", "");
//        saveField(Constant.KEY_SIGNATURE, "");
//        saveField(Constant.KEY_NICKNAME, "");
//        saveField(Constant.KEY_TYPE, "");
//        saveField(Constant.KEY_USERID, "");
//        saveField(Constant.KEY_PHOTO, "");
//        saveField(Constant.KEY_MOBILE, "");
//        saveField(Constant.KEY_WEALTH, "");
//        saveField(Constant.KEY_USERID_CHATTER, "");
//        saveField(Constant.KEY_AVATAR_CHATTER, "");
//        saveField(Constant.KEY_NICKNAME_CHATTER, "");
//        saveField(Constant.KEY_CHATTER_PRICE,"");
//        saveField(Constant.CHATTED_TIME_STORAGE,"");
//    }
    public void goAgreement() {
        Intent intent = new Intent(this, WebViewActivity.class);
        intent.putExtra(Constant.KEY_WEB_VIEW_TITLE, "用户协议");
        intent.putExtra(Constant.KEY_WEB_VIEW_URL, Constant.REGISTER_AGREEMENT);
        startActivity(intent);
    }

    public void goPrivateAgreement() {
        Intent intent = new Intent(this, WebViewActivity.class);
        intent.putExtra(Constant.KEY_WEB_VIEW_TITLE, "隐私协议");
        intent.putExtra(Constant.KEY_WEB_VIEW_URL, Constant.PRIVATE_AGREEMENT);
        startActivity(intent);
    }

    //    public void showPermissionIntroDialog(BasePopupView popupView) {
//        new XPopup.Builder(this)
//                .popupAnimation(PopupAnimation.ScaleAlphaFromCenter)
//                .isRequestFocus(false)
//                .asCustom(popupView)
//                .show();
//    }
//
//    public void showPermissionIntroDialog(String title, String desc, OnPermissionIntroClickListener listener) {
//        PermissionIntroDialog dialog = new PermissionIntroDialog(this, R.layout.dialog_permission_intro, listener);
//        TextView tvTitle = dialog.findViewById(R.id.tvTitle);
//        TextView tvDesc = dialog.findViewById(R.id.tvDesc);
//        tvTitle.setText(title);
//        tvDesc.setText(desc);
//        new XPopup.Builder(this)
//                .popupAnimation(PopupAnimation.ScaleAlphaFromCenter)
//                .isRequestFocus(false)
//                .asCustom(dialog)
//                .show();
//    }
    public void checkOpenGallery(Context context) {
        if (XXPermissions.isGranted(this, Permission.WRITE_EXTERNAL_STORAGE) && !XXPermissions.isGranted(this, Permission.CAMERA)) {
            showPermissionIntroDialog(getString(R.string.permission_camera_title), getString(R.string.permission_camera_desc), new OnPermissionIntroClickListener() {
                @Override
                public void onClickCancel() {
                    openGallery(false);
                }

                @Override
                public void onClickOK() {
                    XXPermissions.with(context)
                            .permission(Permission.CAMERA)
                            .request(new OnPermissionCallback() {
                                @Override
                                public void onGranted(List<String> permissions, boolean all) {
                                    openGallery(true);
                                }

                                @Override
                                public void onDenied(List<String> permissions, boolean never) {
                                    openGallery(false);
                                }
                            });

                }
            });
        } else if (XXPermissions.isGranted(this, Permission.CAMERA) && !XXPermissions.isGranted(this, Permission.WRITE_EXTERNAL_STORAGE)) {
            showPermissionIntroDialog(getString(R.string.permission_storate_title), getString(R.string.permission_storate_desc), new OnPermissionIntroClickListener() {
                @Override
                public void onClickCancel() {
                    openGallery(true);

                }

                @Override
                public void onClickOK() {
                    XXPermissions.with(context)
                            .permission(Permission.READ_EXTERNAL_STORAGE, Permission.WRITE_EXTERNAL_STORAGE)
                            .request(new OnPermissionCallback() {
                                @Override
                                public void onGranted(List<String> permissions, boolean all) {
                                    openGallery(true);
                                }

                                @Override
                                public void onDenied(List<String> permissions, boolean never) {
                                    showPermissionIntroDialog(getString(R.string.permission_denied_title), "没有相关权限，无法打开相册", null);
                                }
                            });
                }
            });
        } else if (!XXPermissions.isGranted(this, Permission.WRITE_EXTERNAL_STORAGE) && !XXPermissions.isGranted(this, Permission.CAMERA)) {
            showPermissionIntroDialog(new String[]{getString(R.string.permission_storate_title), getString(R.string.permission_camera_title)}, new String[]{getString(R.string.permission_storate_desc), getString(R.string.permission_camera_desc)}, new OnPermissionIntroClickListener() {
                @Override
                public void onClickOK() {
                    XXPermissions.with(context)
                            .permission(Permission.READ_EXTERNAL_STORAGE, Permission.WRITE_EXTERNAL_STORAGE, Permission.CAMERA)
                            .request(new OnPermissionCallback() {
                                @Override
                                public void onGranted(List<String> permissions, boolean all) {
                                    if (all) {
                                        openGallery(true);
                                    } else {
                                        if (permissions.contains(Permission.CAMERA)) {
                                            showPermissionIntroDialog(getString(R.string.permission_denied_title), "没有相关权限，无法打开相册", null);
                                        } else {
                                            openGallery(false);
                                        }
                                    }
                                }

                                @Override
                                public void onDenied(List<String> permissions, boolean never) {
                                    if (permissions.contains(Permission.WRITE_EXTERNAL_STORAGE)) {
                                        showPermissionIntroDialog(getString(R.string.permission_denied_title), "没有相关权限，无法打开相册", null);
                                    }
                                }
                            });
                }

                @Override
                public void onClickCancel() {

                }
            });
        } else {
            openGallery(true);
        }
    }

    private void openGallery(boolean showCamera) {
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())// 单独拍照，也可录像或也可音频 看你传入的类型是图片or视频
                .imageEngine(GlideEngine.createGlideEngine())
                .isWeChatStyle(true)
//                        .theme(themeId)// 主题样式设置 具体参考 values/styles
                .maxSelectNum(1)// 最大图片选择数量
                .minSelectNum(1)// 最小选择数量
                .selectionMode(PictureConfig.SINGLE)// 多选 or 单选
                .isPreviewImage(true)
                .isCamera(showCamera)// 是否显示拍照按钮
                .minimumCompressSize(100)// 小于100kb的图片不压缩
                .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
    }

    public int getColorX(int colorId) {
        return ContextCompat.getColor(this, colorId);
    }
}
